<?php
/*
stardevelop.com Live Help
International Copyright stardevelop.com

You may not distribute this program in any manner,
modified or otherwise, without the express, written
consent from stardevelop.com

You may make modifications, but only for your own 
use and within the confines of the License Agreement.
All rights reserved.

Selling the code for this program without prior 
written consent is expressly forbidden. Obtain 
permission before redistributing this program over 
the Internet or in any other medium.  In all cases 
copyright and header must remain intact.  
*/
include('./include/spiders.php');
include('./include/database.php');
include('./include/class.mysql.php');
include('./include/config.php');
include('./include/version.php');

if (!isset($_REQUEST['USER'])){ $_REQUEST['USER'] = ''; }
if (!isset($_REQUEST['EMAIL'])){ $_REQUEST['EMAIL'] = ''; }
if (!isset($_REQUEST['QUESTION'])){ $_REQUEST['QUESTION'] = ''; }
if (!isset($_REQUEST['DEPARTMENT'])){ $_REQUEST['DEPARTMENT'] = ''; }
if (!isset($_REQUEST['SERVER'])){ $_REQUEST['SERVER'] = ''; }
if (!isset($_REQUEST['URL'])){ $_REQUEST['URL'] = ''; }

$username = $_REQUEST['USER'];
$email = $_REQUEST['EMAIL'];
$question = $_REQUEST['QUESTION'];
$department = $_REQUEST['DEPARTMENT'];
$referer = $_REQUEST['URL'];
$ip_address = $_SERVER['REMOTE_ADDR'];

if ($_REQUEST['COOKIE'] != '') {
	$cookie_domain = $_REQUEST['COOKIE'];
}

if ($_SETTINGS['REQUIREGUESTDETAILS'] == true && $_SETTINGS['LOGINDETAILS'] == true) {

	if ($username == '' || ($email == '' && $_SETTINGS['LOGINEMAIL'] == true)) {
		if ($department == '') {
			header('Location: index.php?ERROR=empty');
			exit();
		}
		else {
			header('Location: index.php?ERROR=empty&DEPARTMENT=' . $department);
			exit();
		}
	}
	else if ($_SETTINGS['LOGINEMAIL'] == true) {
		if (!ereg('^[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+'.
			'@'.
			'[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.'.
			'[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$', $email)) {
			if ($department == '') {
				header('Location: index.php?ERROR=email');
				exit();
			}
			else {
				header('Location: index.php?ERROR=email&DEPARTMENT=' . $department);
				exit();
			}
		}
	}
}

if ($department == '') { $department = $_REQUEST['DEPARTMENT']; }

// Query to see if Admin/Operators are Online
$query = "SELECT UNIX_TIMESTAMP(`datetime`) AS `datetime` FROM " . $table_prefix . "users WHERE (UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(`refresh`)) < '$connection_timeout' AND `status` = '1'";
if ($_SETTINGS['DEPARTMENTS'] == true && $department != '') { $query .= " AND department LIKE '%$department%'"; }
$row = $SQL->selectquery($query);
if(is_array($row)) {
	$datetime = $row['datetime'];
}
else {
	header('Location: offline.php?SERVER=' . $_REQUEST['SERVER']);
	exit();
}

$server = $_SETTINGS['URL'];

// Get the applicable hostname to show where the site visitor is located
$query = "SELECT `url` FROM " . $table_prefix . "requests WHERE `id` = '$request_id'";
$row = $SQL->selectquery($query);
if (is_array($row)) {
	$server = $row['url'];

	for ($i = 0; $i < 3; $i++) {
		$substr_pos = strpos($server, '/');
		if ($substr_pos === false) {
			break;
		}
		if ($i < 2) {
			$server = substr($server, $substr_pos + 1);
		}
		else {
			$server = substr($server, 0, $substr_pos);
		}
	
	}
	
	if (substr($server, 0, 4) == 'www.') { $server = substr($server, 4); }

}


if ($username == '') { $username = 'Guest'; }

// If the site visitor has chatted previously then start new session 
if ($guest_login_id == 0) {
	// Add session details
	$query = "INSERT INTO " . $table_prefix . "sessions (`request`, `username`, `datetime`, `email`, `question`, `server`, `department`, `refresh`) VALUES ('$request_id', '$username', NOW(), '$email', '$question', '$server', '$department', NOW())";
	$login_id = $SQL->insertquery($query);
}
else {
	$login_id = $guest_login_id;
	
	// Retrieve the current connected server
	$query = "SELECT `server` FROM " . $table_prefix . "sessions WHERE `id` = '$login_id'";
	$row = $SQL->selectquery($query);
	if (is_array($row)) {
		$server = $row['server'];
		
		// Update session details
		$query = "UPDATE " . $table_prefix . "sessions SET `request` = '$request_id', `username` = '$username', `datetime` = NOW(), `email` = '$email', `question` = '$question', `server` = '$server', `department` = '$department', `refresh` = NOW(), `active` = '0' WHERE `id` = '$login_id'";
		$SQL->miscquery($query);
	}  
	else {
		// Add session details
		$query = "INSERT INTO " . $table_prefix . "sessions (`request`, `username`, `datetime`, `email`, `question`, `server`, `department`, `refresh`) VALUES ('$request_id', '$username', NOW(), '$email', '$question', '$server', '$department', NOW())";
		$login_id = $SQL->insertquery($query);
	}
}
	
// Remove the Initate chat flag and flag as chatting from the requests as the chat has started.
$query = "UPDATE " . $table_prefix . "requests SET `initiate` = '-4' WHERE `id` = '$request_id'";
$SQL->miscquery($query);

// Retrieve the current connected server
if ($server != '') {
	$query = "SELECT `server` FROM " . $table_prefix . "sessions WHERE `id` = '$login_id'";
	$row = $SQL->selectquery($query);
	if (is_array($row)) {
		$server = $row['server'];
	}
}

$session = array();
$session['REQUEST'] = $request_id;
$session['GUEST_LOGIN_ID'] = $login_id;
$session['GUEST_USERNAME'] = $username;
$session['MESSAGE'] = 0;
$session['OPERATOR'] = '';
$session['TOTALOPERATORS'] = 0;
$session['SECURITY'] = $security;
$session['LANGUAGE'] = LANGUAGE_TYPE;
$session['DOMAIN'] = $cookie_domain;
$data = serialize($session);

setCookie('LiveHelpSession', $data, false, '/', $cookie_domain, 0);

$chat = array();
$chat['USER'] = $_REQUEST['USER'];
$chat['EMAIL'] = $_REQUEST['EMAIL'];
$chat['DEPARTMENT'] = $_REQUEST['DEPARTMENT'];
$chat['QUESTION'] = $_REQUEST['QUESTION'];

$data = serialize($chat);
setcookie('LiveHelpChat', $data, false, '/', $cookie_domain, 0);

header('Content-type: text/html; charset=utf-8');

if ($_SETTINGS['CAMPAIGNIMAGE'] == '') {
	$width = '580';
	$column = '514';
} else {
	$width = '450';
	$column = '444';
}

if (file_exists('./locale/' . LANGUAGE_TYPE . '/guest.php')) {
	include('./locale/' . LANGUAGE_TYPE . '/guest.php');
}
else {
	include('./locale/en/guest.php');
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title><?php echo($_SETTINGS['NAME']); ?></title>
<script language="JavaScript" type="text/JavaScript" src="./scripts/guest.js.php?ID=<?php echo($login_id); ?>&amp;USER=<?php echo($username); ?>&amp;COOKIE=<?php echo($_REQUEST['COOKIE']); ?>&amp;LANGUAGE=<?php echo(LANGUAGE_TYPE); ?>"></script>
<style type="text/css">
<!--
.background {
	background-image: url(./locale/<?php echo(LANGUAGE_TYPE); ?>/images/background.gif);
	background-repeat: no-repeat;
	background-position: center top;
	margin: 0px;
	text-align: center;
	min-width: 600px;
}

-->
</style>
<script language="JavaScript" type="text/javascript">
<!--

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

//-->
</script>
<link href="styles/styles.php" rel="stylesheet" type="text/css"/>
</head>
<body bgcolor="<?php echo($_SETTINGS['BACKGROUNDCOLOR']); ?>" text="<?php echo($_SETTINGS['FONTCOLOR']); ?>" link="<?php echo($_SETTINGS['LINKCOLOR']); ?>" vlink="<?php echo($_SETTINGS['LINKCOLOR']); ?>" alink="<?php echo($_SETTINGS['LINKCOLOR']); ?>" onload="preloadImages('./locale/<?php echo(LANGUAGE_TYPE); ?>/images/send_hover.gif'); LoadMessages();" onunload="windowLogout();" class="background" onkeydown="focusChat();" style="margin-bottom:0px;">
<?php if ($_SETTINGS['LOGO'] != '') { ?>
<div style="margin:0 auto; text-align:left; width:600px;">
<img src="<?php echo($_REQUEST['SERVER'] . $_SETTINGS['LOGO']); ?>" alt="<?php echo($_SETTINGS['NAME']); ?>" border="0" style="position:relative; top:15px; left:15px;"/>
<a href="#" onclick="self.displayFrame.displayContentsFrame.focus(); self.displayFrame.displayContentsFrame.print(); return false;"  onmouseout="MM_swapImgRestore()" onmouseover="MM_swapImage('Print','','./locale/<?php echo(LANGUAGE_TYPE); ?>/images/print_tab_over.gif',1)" target="_top"><img src="./locale/<?php echo(LANGUAGE_TYPE); ?>/images/print_tab.gif" alt="<?php echo($print_chat_label); ?>" name="Print" width="60" height="18" border="0" id="Print" style="position:relative; left:310px; top:45px; z-index:1000;"/><img src="./images/fileprint.gif" alt="<?php echo($print_chat_label); ?>" style="position:relative; left:242px; top:48px; z-index:2000;" border="0"/></a>
<?php
} else {
?>
<div style="margin:0 auto; text-align:left; width:600px; margin-top:30px;">
<a href="#" onclick="self.displayFrame.displayContentsFrame.focus(); self.displayFrame.displayContentsFrame.print(); return false;"  onmouseout="MM_swapImgRestore()" onmouseover="MM_swapImage('Print','','./locale/<?php echo(LANGUAGE_TYPE); ?>/images/print_tab_over.gif',1)" target="_top"><img src="./locale/<?php echo(LANGUAGE_TYPE); ?>/images/print_tab.gif" alt="<?php echo($print_chat_label); ?>" name="Print" width="60" height="18" border="0" id="Print" style="position:relative; left:520px; top:43px; z-index:1000;"/><img src="./images/fileprint.gif" alt="<?php echo($print_chat_label); ?>" style="position:relative; left:452px; top:46px; z-index:2000;" border="0"/></a>
<?php
}
?>
  <img src="./locale/<?php echo(LANGUAGE_TYPE); ?>/images/waiting.gif" alt="Typing Status" name="messengerStatus" id="messengerStatus" style="position:absolute; top:327px; left:355px;"/>
  <table width="100%" border="0" cellpadding="0" cellspacing="0" style="position:relative; top:20px;">
    <tr>
      <td><table width="100%" border="0" align="left" cellpadding="4" cellspacing="4" style="margin:0px;">
          <tr>
            <td rowspan="3"><table width="<?php echo($width); ?>" border="0" align="left" cellpadding="0" cellspacing="0">
                <tr>
                  <td width="3" height="3" style="background-image:url(images/border-top-left.gif); background-repeat:no-repeat;"></td>
                  <td width="<?php echo($column); ?>" height="3"></td>
                  <td width="3" height="3" style="background-image:url(images/border-top-right.gif); background-repeat:no-repeat;"></td>
                </tr>
                <tr>
                  <td width="3" height="3" style="background-image:url(images/border-left.gif); background-repeat:repeat-y"></td>
                  <td width="<?php echo($column); ?>" height="240" bgcolor="#FFFFFF"><iframe name="displayFrame" id="displayFrame" src="displayer.php?LANGUAGE=<?php echo(LANGUAGE_TYPE); ?>" frameborder="0" width="100%" height="100%" style="border:none;">
                    <script language="JavaScript" type="text/JavaScript">self.location.href = 'offline.php';</script>
                    </iframe></td>
                  <td width="3" height="3" style="background-image:url(images/border-right.gif); background-repeat:repeat-y"></td>
                </tr>
                <tr>
                  <td width="3" height="3" style="background-image:url(images/border-bottom-left.gif); background-repeat:no-repeat;"></td>
                  <td width="<?php echo($column); ?>" height="3" style="background-image:url(images/border-bottom.gif); background-repeat:repeat-x;"></td>
                  <td width="3" height="3" style="background-image:url(images/border-bottom-right.gif); background-repeat:no-repeat"></td>
                </tr>
              </table></td>
            <td height="18"></td>
          </tr>
          <?php if ($_SETTINGS['CAMPAIGNIMAGE'] != '') { ?>
          <tr>
            <td valign="top">
              <div align="center">
                <?php if ($_SETTINGS['CAMPAIGNLINK'] != '') { ?>
                <a href="<?php echo($_SETTINGS['CAMPAIGNLINK']); ?>" target="_blank">
                <?php } ?>
                <img src="<?php echo($_SETTINGS['CAMPAIGNIMAGE']); ?>" border="0" alt="Live Help - Welcome, how can I be of assistance?"/>
                <?php if ($_SETTINGS['CAMPAIGNLINK'] != '') { ?>
                </a>
                <?php } ?>
              </div>
            </td>
          </tr>
          <?php } ?>
        </table></td>
    </tr>
    <tr>
      <td></td>
    </tr>
  </table>
  <div id="Background" style="position:absolute; left:435px; top:288px; z-index:1; visibility: hidden;"><img src="images/smilies_background.gif" onmouseout="toggleLayer('Background'); toggleLayer('Smilies'); return false;" onmouseover="toggleLayer('Background', null, true); toggleLayer('Smilies', null, true); return false;" alt="Emoticons (Smilies)"/></div>
  <div id="Smilies" style="position:absolute; padding: 5px; left:440px; top:293px; width:160px; height:75px; z-index:2; visibility: hidden;" onmouseout="toggleLayer('Background'); toggleLayer('Smilies'); return false;" onmouseover="toggleLayer('Background', null, true); toggleLayer('Smilies', null, true); return false;">
    <div align="center"><a href="#" onclick="appendText(':-)'); toggleLayer('Smilies'); return false;"><img src="images/smilie1.gif" width="20" height="20" border="0" alt="Smile :-)"/></a><a href="#" onclick="appendText(';-P'); toggleLayer('Smilies'); return false;"><img src="images/smilie4.gif" width="21" height="20" border="0" alt="Smile with tongue out ;-P"/></a><a href="#" onclick="appendText(':)'); toggleLayer('Smilies'); return false;"><img src="images/smilie8.gif" width="20" height="20" border="0" alt="Smile :)"/></a><a href="#" onclick="appendText('$-D'); toggleLayer('Smilies'); return false;"><img src="images/smilie3.gif" width="20" height="21" border="0" alt="Smile with money eyes $-D"/></a><a href="#" onclick="appendText('8-)'); toggleLayer('Smilies'); return false;"><img src="images/smilie7.gif" width="21" height="20" border="0" alt="Hot Smile 8-)"/></a><a href="#" onclick="appendText(':-/'); toggleLayer('Smilies'); return false;"><img src="images/smilie5.gif" width="20" height="20" border="0" alt="Confused Smile :-/"/></a><a href="#" onclick="appendText(':-O'); toggleLayer('Smilies'); return false;"><img src="images/smilie12.gif" width="20" height="20" border="0" alt="Suprised smile :-O"/></a><a href="#" onclick="appendText(':('); toggleLayer('Smilies'); return false;"><img src="images/smilie6.gif" width="20" height="21" border="0" alt="Sad smile :("/></a><a href="#" onclick="appendText(':-('); toggleLayer('Smilies'); return false;"><img src="images/smilie2.gif" width="20" height="20" border="0" alt="Sad Smile :-("/></a><a href="#" onclick="appendText(':-|'); toggleLayer('Smilies'); return false;"><img src="images/smilie9.gif" width="20" height="20" border="0" alt="Disappointed Smile :-|"/></a><a href="#" onclick="appendText(':--'); toggleLayer('Smilies'); return false;"><img src="images/smilie10.gif" width="20" height="20" border="0" alt="Thinking Smile :--"/></a><a href="#" onclick="appendText('/-|'); toggleLayer('Smilies'); return false;"><img src="images/smilie11.gif" width="21" height="20" border="0" alt="Angry /-|"/></a></div>
  </div>
  <iframe id="sendMessageFrame" name="sendMessageFrame" src="blank.php" frameborder="0" width="0" height="0" style="visibility:hidden; border:none;"></iframe>
  <form action="send.php" method="post" name="MessageForm" target="sendMessageFrame" style="margin: 0px; position: relative; top: 25px;">
    <table width="100%" border="0" align="center" cellpadding="2" cellspacing="2" style="margin: 0px;">
      <tr>
        <td width="475"><div align="left">
            <textarea name="MESSAGE" cols="55" rows="3" onkeypress="return checkEnter(event);" onfocus="self.focussed = true;" onblur="typing(false); self.focussed = false" style="width:450px; height:45px; margin-left: 10px; font-family:<?php echo($_SETTINGS['CHATFONT']); ?>; font-size:<?php echo($_SETTINGS['CHATFONTSIZE']); ?>;"></textarea>
            <input name="PREVIOUS" type="hidden" id="PREVIOUS"/>
          </div></td>
        <td><a href="#" onmouseout="swapImgRestore();" onmouseover="swapImage('Send','','./locale/<?php echo(LANGUAGE_TYPE); ?>/images/send_hover.gif',1);" onclick="return processForm();"><img src="./locale/<?php echo(LANGUAGE_TYPE); ?>/images/send.gif" alt="<?php echo($send_msg_label); ?>" name="Send" width="58" height="50" border="0"/></a>&nbsp;<a href="#" onmouseout="toggleLayer('Background'); toggleLayer('Smilies'); return false;" onmouseover="toggleLayer('Background', null, true); toggleLayer('Smilies', null, true); return false;"><img src="images/smilie1.gif" alt="<?php echo($add_smilie_label); ?>" name="Smilies" border="0" style="position:relative; top: -27px; left: 8px;"/></a></td>
      </tr>
      <tr>
        <td colspan="2"><div align="center"><span class="small">International Copyright &copy; <?php echo date('Y');?> Date Sand Models Live Help All Rights Reserved</span></div></td>
      </tr>
    </table>
  </form>
  <script language="JavaScript" type="text/JavaScript">
<!--//

function processForm() {

	var message = document.MessageForm.MESSAGE.value

	if (message != '') {
		if (initalisedChat == 0) {
			void(document.MessageForm.submit());
			document.MessageForm.MESSAGE.value = '';
		}
		else {
			typing(false);
			
			message = removeHTML(message);
			self.display(self.SentMessage + 1, '<?php echo($username); ?>', message, '1', '0');
			self.bottom();
			
			void(document.MessageForm.submit());
			document.MessageForm.MESSAGE.value = '';
		}
	}
  	return false;
}

function appendText(text) {
	if (!self.document.MessageForm.MESSAGE.disabled) {
		var current = document.MessageForm.MESSAGE.value;
		document.MessageForm.MESSAGE.value = current + text;
	}
}

function checkEnter(e) {
	var characterCode;
	typing(true);

	if (e.keyCode == 13 || e.charCode == 13) {
		processForm();
		return false;
	} else {
		return true;
	}
}

//-->
</script>
</div>
</body>
</html>
